#!/usr/bin/env python
import cgi
import urllib
import urllib2
import httplib
from xml.dom import minidom

form = cgi.FieldStorage() 

if form.has_key('pelicula'): pel=form.getvalue('pelicula')
if form.has_key('usuario'): user=form.getvalue('usuario')
if form.has_key('comentario'): comment=form.getvalue('comentario')
if form.has_key('rating'): rating=form.getvalue('rating')

#Chequeamos el registro. Necesitamos la BD.
parametros = urllib.urlencode({"_query":"//pelicula[@name='"+pel+"']","_wrap":"no"})
respuesta = urllib2.urlopen("http://localhost:8080/exist/rest/db/comentarios/?"+parametros)
respuesta = respuesta.read()

if respuesta=='':
	modificacion = """<xupdate:modifications version="1.0"  xmlns:xupdate="http://www.xmldb.org/xupdate">
	<xupdate:insert-before select="//pelicula[1]" >  
		<xupdate:element name="pelicula">
			<xupdate:attribute name="name">"""+pel+"""</xupdate:attribute>
			<xupdate:element name="comentario">
				<xupdate:attribute name="user">"""+user+"""</xupdate:attribute>
				<xupdate:attribute name="rating">"""+rating+"""</xupdate:attribute>
					<xupdate:element name="titulo">"""+pel+"""</xupdate:element> 
					<xupdate:element name="texto">"""+comment+"""</xupdate:element>
			
			</xupdate:element>  
		</xupdate:element> 
	</xupdate:insert-before> 
	</xupdate:modifications>""" 
	
	conn = httplib.HTTP("localhost:8080")
	conn.putrequest("POST", "/exist/rest/db/comentarios")
	conn.putheader('Content-Type', 'text/xml')
	clen = len(modificacion)
	conn.putheader('Content-Length', `clen`)
	conn.endheaders()
	conn.send(modificacion)
	response = conn.getreply()
	if response[0]!=200:
		print """\
		Content-Type: text/plain\n
		CommentFail
		"""
	else:
		print """\
		Content-Type: text/plain\n
		CommentAdded
		"""
	conn.close()

else:
	#Hay que buscar el numero de pelicula.
	dom = minidom.parseString(respuesta)
	pelis = dom.getElementsByTagName('pelicula')
	
	
	modificacion = """<xupdate:modifications version="1.0"  xmlns:xupdate="http://www.xmldb.org/xupdate">
	<xupdate:insert-before select="//pelicula[@name='"""+pel+"""']/comentario[1]" >  
		<xupdate:element name="comentario">
				<xupdate:attribute name="user">"""+user+"""</xupdate:attribute>
				<xupdate:attribute name="rating">"""+rating+"""</xupdate:attribute>
					<xupdate:element name="titulo">"""+pel+"""</xupdate:element> 
					<xupdate:element name="texto">"""+comment+"""</xupdate:element>
			
		</xupdate:element>  
	</xupdate:insert-before> 
	</xupdate:modifications>""" 
	
	conn = httplib.HTTP("localhost:8080")
	conn.putrequest("POST", "/exist/rest/db/comentarios")
	conn.putheader('Content-Type', 'text/xml')
	clen = len(modificacion)
	conn.putheader('Content-Length', `clen`)
	conn.endheaders()
	conn.send(modificacion)
	response = conn.getreply()
	if response[0]!=200:
		print """\
		Content-Type: text/plain\n
		CommentFail
		"""
	else:
		print """\
		Content-Type: text/plain\n
		CommentAdded
		"""
	conn.close()
